<template>
  <div class="mt-p-info">
    <group gutter="10">
      <x-input title="供应品种" v-model="kind.name" :readonly="true">
        <x-button type="primary" 
        slot="right" class="weui-btn-primary-blue"
        link="/trade/supplies/post/fishes" mini>重新选择</x-button>
      </x-input>
      <x-input title="标题" 
      :show-clear="false"
      v-model="title"
      placeholder="请输入标题">
      </x-input>
      <x-input class="mt-p-info-unit" title="规格" placeholder="" :readonly="true">
        <div class="mt-p-info-unit-right" slot="right">
          <div class="mt-p-info-unit-right-top clearfix">
            <x-input
            v-if="size_unit_id"
            placeholder="最小规格" 
            :show-clear="false"
            type="number"
            v-model="size_min"></x-input>
            <span v-if="size_unit_id" class="mt-p-info-unit-separtor">-</span>
            <x-input 
            v-if="size_unit_id"
            placeholder="最大规格" 
            :show-clear="false"
            type="number"
            v-model="size_max"></x-input>
            <popup-radio
            v-if="unitSize.length"
            class="mt-p-info-unit-radio mt-p-info-radio"
            :options="unitSize"
            v-model="size_unit_id"
            :placeholder="unitSize[0].value"></popup-radio>
          </div>
          <checker
          v-model="selectedRegularUnit"
          default-item-class="mt-p-info-units"
          selected-item-class="mt-p-info-units-selected"
          radio-required>
            <checker-item 
            v-for="(i, index) in units.regular_size" 
            :key="index" 
            :value="i">{{i | unit}}</checker-item>
          </checker>
        </div>
      </x-input>
      <x-input class="mt-p-info-selltype" title="供应类型">
        <div class="mt-p-info-selltype-right" slot="right">
          <checker
          v-model="sale_type"
          default-item-class="mt-p-info-selltypes"
          selected-item-class="mt-p-info-selltypes-selected"
          >
            <checker-item 
            v-for="(i, index) in sale_types" 
            :key="index" 
            :value="i">
              <div class="mt-p-info-selltypes-cell">
                <span class="mt-p-info-selltypes-top">{{i.value}}</span>
                <span class="mt-p-info-selltypes-bottom">{{i.comment}}</span>
              </div>
            </checker-item>
          </checker>
        </div>
      </x-input>
      <cell v-if="sale_type.key===2"
      title="上市时间" 
      :value="markerTime" 
      is-link 
      class="adjust-arrow"
      @click.native="$router.push({name: 'suppliesBoardSeason'})"></cell>
      <x-input class="mt-p-info-price" 
      title="价格" 
      :show-clear="false" 
      :readonly="!priceWriteable"
      v-model="price"
      :placeholder="pricePlaceholder">
        <div class="mt-p-info-price-right" slot="right">
          <popup-radio
          v-if="units.unit_price"
          class="mt-p-info-radio"
          :options="units.unit_price"
          v-model="price_unit_id"
          :placeholder="units.unit_price[0].value"
          ></popup-radio>
        </div>
      </x-input>
      <x-input class="mt-p-info-stock" 
      title="供货数量" 
      type="number"
      :show-clear="false" 
      v-model="stock"
      placeholder="请输入供货数量">
        <div v-if="stock_unit_id" class="mt-p-info-price-right" slot="right">
          <popup-radio
          v-if="units.stock_types"
          class="mt-p-info-radio"
          :options="units.stock_types"
          v-model="stock_unit_id"
          :placeholder="units.stock_types[0].value"
          ></popup-radio>
        </div>
        <div v-else slot="right">
          {{priceName}}
        </div>
      </x-input>
      <cell 
      class="adjust-arrow"
      title="供货地址" 
      :value="district" 
      is-link 
      @click.native="$router.push({name: 'suppliesBoardProvinces'})"></cell>
      <x-textarea :max="50" 
      placeholder="请填写详细地址，不少于5个字。"
      v-model="address"></x-textarea>
      <x-input class="mt-p-info-valided" :readonly="true" title="供应时间" :show-clear="false">
        <div class="mt-p-info-price-right" slot="right">
          <popup-radio
          v-if="validateTime.length"
          class="mt-p-info-radio"
          :options="validateTime"
          v-model="valided"
          :placeholder="validateTime[0].value"
          ></popup-radio>
        </div>
      </x-input>
      <image-uploader :kind="kind" 
      @changeImage="changeFishImage"
      ref="uploader"></image-uploader>
      <x-textarea title="补充说明" 
      placeholder="可输入特殊说明，如养殖方式、水质、起批数量等情况" 
      :max="50" 
      :show-counter="true" 
      :rows="3"
      v-model="desc">
      </x-textarea>
      <div class="weui-cell mt-p-info-supplements">
        <checker
        v-model="desc_tag"
        type="checkbox"
        :max="2"
        default-item-class="mt-p-info-supplement"
        selected-item-class="mt-p-info-supplement-selected">
          <checker-item 
          v-for="(i) in supplements" 
          :key="i" 
          :value="i">{{i}}</checker-item>
        </checker>
      </div>
    </group>
    <group>
      <x-input title="联系人" v-model="contact_name"></x-input>
      <x-input title="手机" type="tel" v-model="contact_mobile"></x-input>
      <div class="weui-cell mt-p-info-disclaimer">
        <check-icon :value.sync="accept"></check-icon>
        <span>阅读并同意</span>  
        <router-link class="mt-p-info-disclaimer-link" :to="{name: 'suppliesBoardDisclaimer'}">《通心粉社区免责声明》</router-link>
      </div>
      <box gap="10px 10px">
        <x-button type="primary"
        class="weui-btn-primary-blue"
        @click.native="submitFormData">立即发布</x-button>
      </box>
    </group>
    <loading :show="loading"></loading>
  </div>
</template>

<script>
import {
  XInput,
  Group,
  XButton,
  Cell,
  Checker,
  CheckerItem,
  PopupRadio,
  XTextarea,
  CheckIcon,
  Box,
  Toast,
  Loading
} from "vux"
import {
  getSupplyUnits,
  filterUnits,
  parseMarketTime,
  getSupplyFormData,
  resetFormData,
  setFormData
} from "@/modules/trade/posts"
import ImageUploader from "@/components/ImageUploader"
import validator from "validator"
import { pickFirstValue } from "@/modules/util"

export default {
  data() {
    return {
      formType: "save",
      loading: false,
      sale_types: [
        { key: 1, value: "现货", comment: "现在有货" },
        { key: 2, value: "预售", comment: "即将上市" }
      ],
      selectedRegularUnit: "",
      // selectedSupplementTag: "",
      units: "",
      regular_size: "",
      markerTime: "",
      supplements: [],
      validateTime: [],
      title: "",
      size_unit_id: "",
      size_min: "",
      size_max: "",
      sale_type: { key: 1, value: "现货", comment: "现在有货" },
      price_type: 1,
      price: "",
      stock: "",
      price_unit_id: "",
      stock_unit_id: "",
      valided: "",
      desc: "",
      desc_tag: "",
      imgs: [],
      contact_name: "",
      contact_mobile: "",
      accept: true,
      address: "",
      unitSize: [],
      regularSize: [], //常用规格标签
      //表单页面控制数据
      priceWriteable: true,
      pricePlaceholder: "请输入价格",
      stock_unit_id: true, //stockType!==0表示价格面议，储存单位可选,
      fromRouteName: "",
    }
  },
  async mounted() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      let formData
      //修改供应，先获取数据
      if (this.itemId) {
        try {
          formData = await this.getFormData(this.itemId)
          if (formData.data.resp_msg.msg_code === 400) {
            // alert(formData.data.resp_msg.msg_error.message)
            this.$router.push({ name: "trade" })
            return
          }
        } catch (e) {
          this.$router.push({ name: "trade" })
          throw new Error(e.message)
          return
        }
        formData = formData.data.resp_data
        if (formData.kind_id !== this.kind.id) {
          this.$store.commit("changeKind", {
            id: formData.kind_id,
            name: formData.kind_name,
            img_view: formData.img_view,
            img: formData.img
          })
        }
      }
      this.$refs.uploader.reset()
      //补充说明标签
      const getSupplements = this.$store.dispatch("getSupplements")
      const getSupplyUnits = this.getSupplyUnits(this.kind.id)
      const validateTime = this.getValidateTime()
      Promise.all([getSupplements, validateTime, getSupplyUnits])
        .then(v => {
          this.supplements = v[0]
          this.validateTime = v[1]
          this.valided = this.validateTime[0].key
          this.loading = false
          if (this.itemId) {
            setFormData.call(this, formData)
          }
        })
        .catch(e => {
          this.loading = false
        })
    },
    async getFormData(itemId) {
      return axios.get("/api/trade/supply/getItem?id=" + itemId)
    },
    //获取规格参数，并初始化一些数据
    async getSupplyUnits() {
      this.units = await getSupplyUnits(this.kind.id)
      this.unitSize = this.units.unit_size
      if (this.units.unit_size[0].key !== 0) {
        this.size_unit_id = this.units.unit_size[0].key
      }
      this.price_unit_id = this.units.unit_price[0].key
      return
    },
    async getValidateTime() {
      const res = await axios.get("/api/trade/common/getValidityList")
      const times = res.data.resp_data
      return formatTimes(times)
    },
    save(formData) {
      if (this.itemId) {
        formData.id = this.itemId
      }
      return axios
        .post("/api/trade/supply/saveItem", qs.stringify(formData))
        .then(response => {
          let data = response.data
          if (data.resp_msg.msg_code === 400) {
            this.$vux.toast.text(
              pickFirstValue(data.resp_msg.msg_error.errors)[0],
              "middle"
            )
          } else {
            this.$store.commit("setLastPostId", {
              id: data.resp_data.id,
              type: "supply"
            })
            this.$router.push({ name: "suppliesBoardSuccess" })
            resetFormData.call(this)
          }
        })
    },
    submitFormData() {
      if (!this.accept) {
        this.$vux.toast.text("需要阅读并同意《通心粉社区免责声明》", "middle")
        return
      }
      const formData = getSupplyFormData.call(this)
      this.save(formData)
    },
    changeFishImage(imgs) {
      this.imgs = imgs
    }
  },
  computed: {
    //鱼的种类
    kind() {
      return this.$store.state.posts.supply.kind
    },
    //需要在vuex中存储的表单数据
    supply() {
      return this.$store.state.posts.supply
    },
    //转为可读的地区
    district() {
      const supplies = this.$store.state.posts.supply
      return (
        convert(supplies.province.name) +
        convert(supplies.city.name) +
        convert(supplies.area.name) +
        convert(supplies.town.name)
      )
    },
    //预售时间
    sale_pre() {
      return this.$store.state.posts.supply.sale_pre
    },
    //如果当前路由所在的是修改供应，则有此参数
    itemId() {
      if (
        this.$route.name === "suppliesEditBoard" ||
        this.$route.name === "suppliesBoardFishes"
      ) {
        // console.log(this.$route.name)
        // console.log("itemId change")

        return this.$route.params.id
      }
    },
    priceName() {
      if(this.price_unit_id !== 0) {
        let name 
        for(let k in this.units.stock_types) {
          if(this.units.stock_types[k].key == this.price_unit_id) {
            return this.units.stock_types[k].value
          }
        }
      }
    }
  },
  watch: {
    $route(to, from) {
      this.fromRouteName = from.name
    },
    //切换鱼类后数据初始化
    kind(v, ov) {
      if (ov.id && v.id) {
        // console.log(321321)
        resetFormData.call(this, 2) //清空除开价格、规格和kind后的其他字段
        console.log(v)
        this.init() //初始化规格数据
      }
    },
    desc(v, ov) {
      if(v.length === 50) {
        this.$vux.toast.text("补充说明不能超过50个字~", "middle")
      }
    },
    address(v,ov) {
      if(v.length === 50) {
        this.$vux.toast.text("详细地址不能超过50个字~", "middle")
      }
    },
    itemId(v, ov) {
      // console.log(v,ov)
      if (
        v !== ov &&
        this.fromRouteName !== "suppliesBoardAddress" &&
        this.fromRouteName !== "suppliesBoardSeason" &&
        this.fromRouteName !== "suppliesEditBoard" &&
        this.fromRouteName !== "suppliesBoardFishes"
      ) {
        resetFormData.call(this)
        this.init()
      }
    },
    size_unit_id(v, ov) {
      if (!v) {
        this.selectedRegularUnit = {
          unit_size_name: "规格不限",
          unit_size_id: 0
        }
      } else if (this.selectedRegularUnit.unit_size_id === 0) {
        this.selectedRegularUnit = ""
      }
    },
    selectedRegularUnit(v, ov) {
      if (v.unit_size_id === 0) {
        this.size_unit_id = 0
        // this.stock_unit_id = this.units.stock_types[0].key
        this.size_min = ""
        this.size_max = ""
      } else if (v.unit_size_id > 0) {
        this.size_unit_id = v.unit_size_id
        this.size_min = v.min
        this.size_max = v.max
      }
    },
    //观察price_unit_id，判断price_type，0面议
    price_unit_id(key) {
      if (key === 0) {
        this.price = ""
        this.price_type = 2
        this.stock_unit_id = this.units.stock_types[0].key
        this.priceWriteable = false
        this.pricePlaceholder = ""
      } else {
        this.price_type = 1
        this.stock_unit_id = 0
        this.priceWriteable = true
        this.pricePlaceholder = "请输入价格"
      }
    },
    //将sale_pre转为可显示的格式
    sale_pre(v) {
      if (!v.year) {
        this.markerTime = ""
      } else {
        this.markerTime = `${v.year}年${v.month}月${v.day}`
      }
    },
    desc_tag(v, ov) {
      if(v.length === 3 && ov.length === 3) {
        this.$vux.toast.text("最多选择三个说明标签", "middle")
      }
    }
  },
  filters: {
    unit: filterUnits
  },
  components: {
    XInput,
    XButton,
    Group,
    Cell,
    Checker,
    CheckerItem,
    PopupRadio,
    XTextarea,
    ImageUploader,
    CheckIcon,
    Box,
    Loading
  }
}

//undefined转空数组
function convert(v) {
  if (v === undefined || v === null) return ""
  else return v
}

function formatTimes(times) {
  return times.map(v => {
    return {
      key: v.valided,
      value: v.day + "天"
    }
  })
}
</script>

<style lang="scss">
@import "../../../../styles/common/trade/trade-form.scss";
</style>
